#include <iostream>  
#include <cstring>  
#include <sys/socket.h>  
#include <arpa/inet.h>  
#include <unistd.h>  
#include <netdb.h>  
  
int main() {  
    const char* server_ip = "127.0.0.1"; // 服务器 IP 地址  
    int server_port = 9000; // 服务器端口号  
    const char* message = "Hello, server!"; // 要发送的消息  
  
    // 创建 socket  
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);  
    if (sockfd < 0) {  
        std::cerr << "Error creating socket" << std::endl;  
        return 1;  
    }  
  
    // 设置服务器地址信息  
    struct sockaddr_in server_addr;  
    memset(&server_addr, 0, sizeof(server_addr));  
    server_addr.sin_family = AF_INET;  
    server_addr.sin_port = htons(server_port);  
    inet_pton(AF_INET, server_ip, &server_addr.sin_addr);  
  
    // 连接到服务器  
    if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {  
        std::cerr << "Error connecting to server" << std::endl;  
        close(sockfd);  
        return 1;  
    }  
  
    // 发送消息到服务器
    sleep(1);
    if (send(sockfd, message, strlen(message), 0) < 0) {  
        std::cerr << "Error sending message to server" << std::endl;  
        close(sockfd);  
        return 1;  
    }  
  
    // 接收服务器的响应  
    char buffer[1024];  
    int bytes_read = recv(sockfd, buffer, sizeof(buffer) - 1, 0);  
    if (bytes_read < 0) {  
        std::cerr << "Error receiving from server" << std::endl;  
    } else {  
        buffer[bytes_read] = '\0'; // 确保字符串以 null 结尾  
        std::cout << "Received from server: " << buffer << std::endl;  
    }  
  
    // 关闭 socket  
    close(sockfd);  
  
    return 0;  
}
